import {
  Button,
  Form,
  Input,
  Image,
  message,
} from 'antd';
import React, { useCallback, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { postAddBannerItemApi } from '../../../api/banner';

const AppBannerUpload = () => {
  const history = useHistory()
  const [img, setImg] = useState()
  const handleFileChange = useCallback((e) => {
    const file = e.target.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      setImg(reader.result)
    }
  }, [])
  const handleonFinish = useCallback((values) => {
    if (!img) {
      message.error('请插入图片')
    } else {
      postAddBannerItemApi({ ...values, img }).then(() => {
        history.push('/banner/list')
      })
    }
  }, [img])
  return (
    <Form
      name="basic"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 16 }}
      initialValues={{ remember: true }}
      onFinish={handleonFinish}
      autoComplete="off"
    >
      <Form.Item
        label="Alt"
        name="alt"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="Link"
        name="link"
        rules={[{ required: true, message: 'Please input your password!' }]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item label="图片" required>
        <Input type="file" onChange={handleFileChange} />
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
        <Image src={img} style={{ width: 150 }} />
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 3, span: 16 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  )
}
export default AppBannerUpload
